import request from '@/utils/request'

// 指标探源 -- 从表单数据到后台数据
function formatOrigin(form) {
  const origin = {
    id: form.id,
    matrixId: form.matrixId,
    type: form.cate,
    fromMatrixId: form.fromChartId,
    metricsConfig: JSON.stringify({
      tableId: form.tableId,
      $tableId: form.$tableId,
      field: form.field,
      $field: form.$field,
      compareType: form.compareType,
      $compareType: form.$compareType,
      summary: form.summary,
      $summary: form.$summary,
      formatterCfg: form.formatterCfg,
      chartType: form.chartType,
    }),
    dimensionConfig: JSON.stringify({
      dimension: form.dimension,
      dimensions: form.dimensions,
    }),
    dataFilter: JSON.stringify(form.filters),
    dateConfig: JSON.stringify({
      dateDimension: form.dateDimension,
      $dateDimension: form.$dateDimension,
      dateStyle: form.dateStyle,
      $dateStyle: form.$dateStyle,
    }),
  }

  return origin
}
// 指标探源 -- 从后台数据到表单数据
function parseOrigin(origin) {
  const form = {}
  try {
    form.id = origin.id
    form.cate = origin.type
    form.fromChartId = origin.fromMatrixId
    const metricsConfig = JSON.parse(origin.metricsConfig)
    form.tableId = metricsConfig.tableId
    form.$tableId = metricsConfig.$tableId
    form.field = metricsConfig.field
    form.$field = metricsConfig.$field
    form.compareType = metricsConfig.compareType
    form.$compareType = metricsConfig.$compareType
    form.summary = metricsConfig.summary
    form.$summary = metricsConfig.$summary
    form.formatterCfg = metricsConfig.formatterCfg
    form.chartType = metricsConfig.chartType
    const dimensionConfig = JSON.parse(origin.dimensionConfig)
    form.dimension = dimensionConfig.dimension
    form.dimensions = dimensionConfig.dimensions
    const dataFilter = JSON.parse(origin.dataFilter)
    form.filters = dataFilter
    const dateConfig = JSON.parse(origin.dateConfig)
    form.dateDimension = dateConfig.dateDimension
    form.$dateDimension = dateConfig.$dateDimension
    form.dateStyle = dateConfig.dateStyle
    form.$dateStyle = dateConfig.$dateStyle
  } catch (error) {
    console.log('error=', error)
  }
  return form
}

// 指标探源 - 保存
export function requestMatrixOriginSave(form) {
  const origin = formatOrigin(form)
  return request({
    url: '/matrix/origin/save',
    method: 'post',
    data: origin,
  })
}

// 指标探源 - 获取
export async function requestMatrixOriginGet(matrixId) {
  const rsp = await request({
    url: '/matrix/origin/get',
    method: 'get',
    params: { matrixId },
  })

  if (rsp.success && rsp.data && rsp.data.id) {
    rsp.data = parseOrigin(rsp.data)
  }

  return rsp
}
